package xin.cymall.controller;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xin.cymall.netty.process.MsgProcessor;

import java.util.Iterator;


@Controller
public class IndexController {


    @RequestMapping("/")
    public String login(){
        return "index/login";
    }

    @RequestMapping("login")
    public String login(HttpServletRequest request,Model model){
        chat(request,model);
        return "index/login";
    }

    @RequestMapping("chat")
    public String chat(HttpServletRequest request,Model model){
        String clientIP = getClientIP(request);
        String username=request.getParameter("username");
        username=username+"("+clientIP+")";
        if(StringUtils.isEmpty(username)){
            return "index/login";
        }
        model.addAttribute("username",username);
        return "index/chat";
    }

    @RequestMapping("list")
    @ResponseBody
    public String list(HttpServletRequest request,Model model){

        ChannelGroup onlineUsers = MsgProcessor.onlineUsers;
        StringBuffer userStr = new StringBuffer();
        Iterator<Channel> iterator = onlineUsers.iterator();
        for (int i=0;i<onlineUsers.size();i++){
            Channel next = iterator.next();
            userStr.append(next.attr(MsgProcessor.USERNAME).get());
            userStr.append(",");
        }
        return userStr.toString();
    }

    public String getClientIP(HttpServletRequest request) {
        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }


}
